import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { User } from './user.entity';
import { CreateUserDto } from './create-user-dto';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { resFormatMethod } from '../../utils/res-format';
import type { JwtPayload } from '../../types/auth.d.ts';
@Injectable()
export class UserService {
  constructor(
    // 注入user这张表的数据库实体
    @InjectRepository(User)
    //userRepository 是针对user这张表的数据库实例
    private readonly userRepository: Repository<User>
  ) {}

  //   里面就可以进行CRUD了

  findOne(id: number): Promise<User | null> {
    return this.userRepository.findOneBy({ id });
  }

  findAll(): Promise<User[]> {
    return this.userRepository.find();
  }

  findByUsername(username: string): Promise<User | null> {
    return this.userRepository.findOneBy({ username });
  }

  async create(createUserDto: CreateUserDto): Promise<User> {
    const user: User = new User();

    user.avatar = createUserDto.avatar || '';
    user.username = createUserDto.username;

    // 盐
    const saltRounds = 10;

    user.password = await bcrypt.hash(createUserDto.password, saltRounds);
    user.roles = createUserDto.roles || '["user"]';
    user.nickname = createUserDto.nickname || '';
    user.active = createUserDto.active || 1;

    return this.userRepository.save(user);
  }

  async delete(id: number): Promise<void> {
    await this.userRepository.delete(id);
  }
  async getUserInfo(payload: JwtPayload) {
    try {
      // 验证payload参数
      if (!payload || !payload.id) {
        throw new UnauthorizedException('无效的用户信息');
      }

      // 从payload中获取用户ID，转换为数字
      const userId =
        typeof payload.id === 'string' ? parseInt(payload.id, 10) : payload.id;

      // 验证ID是否为有效数字
      if (isNaN(userId) || userId <= 0) {
        throw new UnauthorizedException('无效的用户ID');
      }

      // 根据ID查找用户
      const user = await this.userRepository.findOneBy({ id: userId });

      if (!user) {
        throw new UnauthorizedException('用户不存在');
      }

      // 构建完整的用户信息对象，排除敏感字段
      const userInfo = {
        id: user.id,
        username: user.username,
        nickname: user.nickname || user.username, // 如果用户没有昵称的话 就返回用户名
        avatar: 'https://fanblog.top/images/avatar.png',
        roles: user.roles.split(' '),
        createdAt: user.created_at,
        updatedAt: user.updated_at,
        // 添加token状态信息
        tokenStatus: 'valid',
        lastLoginTime: new Date().toISOString(),
      };

      // 返回用户信息（不包含密码等敏感信息）
      const result = resFormatMethod(0, '获取用户信息成功', userInfo);

      return result;
    } catch (error) {
      if (error instanceof UnauthorizedException) {
        throw error;
      }

      throw new UnauthorizedException('获取用户信息失败，请稍后重试');
    }
  }
}
